package com.ccx.library.module.parallel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ccx.library.module.parallel.service.UserRoleService;
import com.ccx.library.module.role.entity.Role;
import com.ccx.library.module.role.service.RoleService;
import com.ccx.library.response.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/userRole")
public class UserRoleController {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @GetMapping("/{username}")
    public R Query(@PathVariable("username") String username){
        return R.SUCCESS(userRoleService.QueryByUsername(username));
    }
    /**
     * 用户绑定角色
     */
    @PostMapping("/bindRole/{roleId}/{userId}")
    public R BindRole(@PathVariable("roleId")String roleId,@PathVariable("userId")String userId){
        return transactionTemplate.execute(Status -> {
            try {
                QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("role_id", roleId);
                Role role = roleService.getOne(queryWrapper);
                List<Role> roles = userRoleService.QueryDownRole(role.getRoleLevel());
                roles.forEach(r->{
                    userRoleService.SaveUR(userId,r.getRoleId());
                });
            }catch (Exception e){
                Status.setRollbackOnly();
                return R.FAIL("绑定失败:"+e);
            }
            return R.SUCCESS();
        });
    }
}
